<?php defined('BASEPATH') OR exit('No direct script access allowed');

/**
 * @package 		925CMS
 * @subpackage 		Latest blog Widget
 * @author			Erik Berman
 *
 * Show Latest blog in your site with a widget. Intended for use on cms pages
 *
 * Usage : on a CMS page add {widget_area('name_of_area')}
 * where 'name_of_area' is the name of the widget area you created in the admin control panel
 */

class Widget_Latest_posts extends Widgets
{
	public $title		= array(
		'vi' => 'Bài viết mới nhất theo chuyên mục'
	);
	public $description	= array(
		'en' => 'Hiển thị danh sách bài viết mới nhất theo chuyên mục',
	);
	public $author		= 'HoangNQ';
	public $website		= 'http://quanghoang.info';
	public $version		= '1.0';

	// build form fields for the backend
	// MUST match the field name declared in the form.php file
	public $fields = array(
        array(
			'field' => 'cat_id',
			'label' => 'Chuyên mục cần hiển thị',
		),
        array(
			'field' => 'limit',
			'label' => 'Số lượng bài viết hiển thị',
		),
	);

	public function form($options)
	{
		!empty($options['limit']) OR $options['limit'] = 5;
		!empty($options['cat_id']) OR $options['cat_id'] = 0;
        $categories = _build_tree_select(array('type'=>'blog_categories', 'current_parent' => $options['cat_id']));

		return array(
			'options' => $options,
            'categories' => $categories
		);
	}

	public function run($options)
	{
		// load the blog module's model
		class_exists('Blog_m') OR $this->load->model('blog/blog_m');

		// sets default number of posts to be shown
		empty($options['limit']) AND $options['limit'] = 5;
		empty($options['cat_id']) AND $options['cat_id'] = 0;

		// retrieve the records using the blog module's model
		$blog_widget = $this->blog_m->limit($options['limit'])->get_many_by(array('status' => 'live', 'category' => $options['cat_id']));

		// returns the variables to be used within the widget's view
		return array('blog_widget' => $blog_widget);
	}
}